<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>回测详情 - 交易策略回测系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: #f5f7fa;
            color: #333;
            padding-bottom: 60px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
        .back-btn {
            display: inline-block;
            padding: 8px 16px;
            background: rgba(255,255,255,0.2);
            color: white;
            text-decoration: none;
            border-radius: 5px;
            margin-bottom: 15px;
            transition: all 0.3s;
        }
        
        .back-btn:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .card {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .card-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .metric-item {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
        }
        
        .metric-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 8px;
        }
        
        .metric-value {
            font-size: 28px;
            font-weight: 600;
            color: #333;
        }
        
        .metric-value.positive {
            color: #48bb78;
        }
        
        .metric-value.negative {
            color: #f56565;
        }
        
        .chart-container {
            margin-top: 20px;
            height: 400px;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }
        
        .info-item {
            display: flex;
            justify-content: space-between;
            padding: 12px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        
        .info-label {
            font-weight: 500;
            color: #666;
        }
        
        .info-value {
            color: #333;
        }
        
        .loading {
            text-align: center;
            padding: 60px;
            color: #999;
            font-size: 18px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #666;
        }
        
        tr:hover {
            background: #f8f9fa;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <a href="/" class="back-btn">← 返回首页</a>
            <h1 id="page-title">回测详情</h1>
            <p id="page-subtitle" style="opacity: 0.9; font-size: 14px;"></p>
        </header>
        
        <div id="loading" class="loading">加载中...</div>
        
        <div id="content" style="display: none;">
            <!-- 关键指标 -->
            <div class="card">
                <div class="card-title">📊 关键指标</div>
                <div class="metrics-grid" id="metrics-grid"></div>
            </div>
            
            <!-- 净值曲线 -->
            <div class="card">
                <div class="card-title">📈 净值曲线</div>
                <div class="chart-container">
                    <canvas id="equity-chart"></canvas>
                </div>
            </div>
            
            <!-- 基本信息 -->
            <div class="card">
                <div class="card-title">ℹ️ 基本信息</div>
                <div class="info-grid" id="info-grid"></div>
            </div>
            
            <!-- 交易记录 -->
            <div class="card">
                <div class="card-title">📝 交易记录 (最近50条)</div>
                <div style="overflow-x: auto;">
                    <table id="trades-table">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>时间</th>
                                <th>品种</th>
                                <th>方向</th>
                                <th>开平</th>
                                <th>数量</th>
                                <th>价格</th>
                                <th>手续费</th>
                            </tr>
                        </thead>
                        <tbody id="trades-tbody"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script>
        // 获取 URL 参数
        const urlParams = new URLSearchParams(window.location.search);
        const backtestId = urlParams.get('id');
        
        if (!backtestId) {
            document.getElementById('loading').textContent = '错误：缺少回测ID';
        } else {
            loadBacktestDetail(backtestId);
        }
        
        async function loadBacktestDetail(id) {
            try {
                const response = await fetch(`/api/backtest/${id}`);
                const data = await response.json();
                
                if (data.error) {
                    document.getElementById('loading').textContent = '错误：' + data.error;
                    return;
                }
                
                // 显示内容
                document.getElementById('loading').style.display = 'none';
                document.getElementById('content').style.display = 'block';
                
                // 更新标题
                const result = data.result;
                document.getElementById('page-title').textContent = 
                    `${result.strategy_name} - ${result.symbol}`;
                document.getElementById('page-subtitle').textContent = 
                    `回测期间: ${result.start_date} 至 ${result.end_date}`;
                
                // 显示关键指标
                displayMetrics(result);
                
                // 显示基本信息
                displayInfo(result);
                
                // 绘制净值曲线
                drawEquityCurve(data.account_records, result.init_balance);
                
                // 显示交易记录
                displayTrades(data.trades);
                
            } catch (error) {
                document.getElementById('loading').textContent = '加载失败：' + error.message;
            }
        }
        
        function displayMetrics(result) {
            const metrics = [
                {
                    label: '总收益率',
                    value: (result.total_return * 100).toFixed(2) + '%',
                    class: result.total_return >= 0 ? 'positive' : 'negative'
                },
                {
                    label: '年化收益率',
                    value: (result.annual_yield * 100).toFixed(2) + '%',
                    class: result.annual_yield >= 0 ? 'positive' : 'negative'
                },
                {
                    label: '夏普率',
                    value: result.sharpe_ratio ? result.sharpe_ratio.toFixed(2) : 'N/A',
                    class: ''
                },
                {
                    label: '最大回撤',
                    value: (result.max_drawdown * 100).toFixed(2) + '%',
                    class: 'negative'
                },
                {
                    label: '胜率',
                    value: (result.winning_rate * 100).toFixed(2) + '%',
                    class: ''
                },
                {
                    label: '盈亏比',
                    value: result.profit_loss_ratio ? result.profit_loss_ratio.toFixed(2) : 'N/A',
                    class: ''
                },
                {
                    label: '开仓次数',
                    value: result.open_times || 0,
                    class: ''
                },
                {
                    label: '平仓次数',
                    value: result.close_times || 0,
                    class: ''
                }
            ];
            
            const grid = document.getElementById('metrics-grid');
            grid.innerHTML = metrics.map(m => `
                <div class="metric-item">
                    <div class="metric-label">${m.label}</div>
                    <div class="metric-value ${m.class}">${m.value}</div>
                </div>
            `).join('');
        }
        
        function displayInfo(result) {
            const info = [
                { label: '策略名称', value: result.strategy_name },
                { label: '交易品种', value: result.symbol },
                { label: '开始日期', value: result.start_date },
                { label: '结束日期', value: result.end_date },
                { label: '初始资金', value: result.init_balance.toLocaleString() + ' 元' },
                { label: '最终资金', value: result.final_balance.toLocaleString() + ' 元' },
                { label: '运行时长', value: result.run_duration_seconds ? result.run_duration_seconds.toFixed(2) + ' 秒' : 'N/A' },
                { label: '回测时间', value: new Date(result.created_at).toLocaleString() }
            ];
            
            const grid = document.getElementById('info-grid');
            grid.innerHTML = info.map(i => `
                <div class="info-item">
                    <span class="info-label">${i.label}</span>
                    <span class="info-value">${i.value}</span>
                </div>
            `).join('');
        }
        
        function drawEquityCurve(accountRecords, initBalance) {
            if (!accountRecords || accountRecords.length === 0) {
                document.querySelector('.chart-container').innerHTML = 
                    '<div style="text-align: center; padding: 40px; color: #999;">暂无账户数据</div>';
                return;
            }
            
            const ctx = document.getElementById('equity-chart').getContext('2d');
            
            const dates = accountRecords.map(r => r.trade_date);
            const balances = accountRecords.map(r => r.balance);
            
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: dates,
                    datasets: [{
                        label: '账户权益',
                        data: balances,
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        borderWidth: 2,
                        fill: true,
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return '权益: ' + context.parsed.y.toLocaleString() + ' 元';
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            title: {
                                display: true,
                                text: '日期'
                            },
                            ticks: {
                                maxTicksLimit: 10
                            }
                        },
                        y: {
                            display: true,
                            title: {
                                display: true,
                                text: '账户权益 (元)'
                            },
                            ticks: {
                                callback: function(value) {
                                    return value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
        }
        
        function displayTrades(trades) {
            const tbody = document.getElementById('trades-tbody');
            
            if (!trades || trades.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #999;">暂无交易记录</td></tr>';
                return;
            }
            
            // 只显示最近50条
            const recentTrades = trades.slice(-50).reverse();
            
            tbody.innerHTML = recentTrades.map(trade => `
                <tr>
                    <td>${trade.trade_date}</td>
                    <td>${trade.datetime || '-'}</td>
                    <td>${trade.symbol}</td>
                    <td style="color: ${trade.direction === 'BUY' ? '#48bb78' : '#f56565'}">${trade.direction}</td>
                    <td>${trade.offset}</td>
                    <td>${trade.volume}</td>
                    <td>${trade.price.toFixed(2)}</td>
                    <td>${trade.commission.toFixed(2)}</td>
                </tr>
            `).join('');
        }
    </script>
</body>
</html>
